Debian Codegraph @

ansible_collections/amazon/aws/docs/docsite/rst/aws_ec2_guide.rst

raw
1 .. _ansible_collections.amazon.aws.docsite.dynamic_inventory:
2
3
4 Dynamic Inventory Plugin
5 ========================
6
7 A dynamic inventory plugin allows users to point at data sources to compile the inventory of hosts that Ansible uses to target tasks, either via the ``-i /path/to/file`` and/or ``-i 'host1, host2'`` command line parameters or from other configuration sources.
8
9 When using Ansible with AWS, inventory file maintenance will be a hectic task as AWS frequently changes IPs, autoscaling instances, and more.
10 Once your AWS EC2 hosts are spun up, you'll probably want to talk to them again.
11 With a cloud setup, it's best not to maintain a static list of cloud hostnames in text files.
12 Rather, the best way to handle this is to use the ``aws_ec2`` dynamic inventory plugin.
13
14 The ``aws_ec2`` dynamic inventory plugin makes API calls to AWS to get a list of inventory hosts from Amazon Web Services EC2 in the run time.
15 It gives the EC2 instance details dynamically to manage the AWS infrastructure.
16
17 The plugin will also return instances that were created outside of Ansible and allow Ansible to manage them.
18
19 To start using the ``aws_ec2`` dynamic inventory plugin with a YAML configuration source, create a file with the accepted filename schema documented for the plugin (a YAML configuration file that ends with ``aws_ec2.(yml|yaml)``, e.g., ``demo.aws_ec2.yml``), then add ``plugin: amazon.aws.aws_ec2``. Use the fully qualified name if the plugin is in a collection.
20
21 .. _ansible_collections.amazon.aws.docsite.using_inventory_plugin:
22
23 Authentication
24 ==============
25
26 If your Ansible controller is not in AWS, authentication is handled by either
27 specifying your access and secret key as ENV variables or inventory plugin arguments.
28
29 For environment variables:
30
31 .. code-block:: bash
32
33 export AWS_ACCESS_KEY_ID='AK123'
34 export AWS_SECRET_ACCESS_KEY='abc123'
35
36 The ``AWS_SECURITY_TOKEN`` environment variable can also be used, but is only supported for backward compatibility.
37 The ``AWS_SECURITY_TOKEN`` is a replacement for ``AWS_SESSION_TOKEN`` and it is only needed when you are using temporary credentials.
38
39 Or you can set ``aws_access_key``, ``aws_secret_key``, and ``security_token`` inside the inventory configuration file.
40
41 .. code-block:: yaml
42
43 # demo.aws_ec2.yml
44 plugin: amazon.aws.aws_ec2
45
46 # The access key for your AWS account.
47 aws_access_key: <YOUR-AWS-ACCESS-KEY-HERE>
48 # The secret access key for your AWS account.
49 aws_secret_key: <YOUR-AWS-SECRET-KEY-HERE>
50
51 If you use different credentials for different tools or applications, you can use profiles.
52
53 The ``profile`` argument is mutually exclusive with the ``aws_access_key``, ``aws_secret_key`` and ``security_token`` options.
54 When no credentials are explicitly provided then the AWS SDK (boto3) which Ansible uses will fall back to its configuration files (typically ``~/.aws/credentials``).
55 The shared credentials file has a default location of ``~/.aws/credentials``.
56 You can change the location of the shared credentials file by setting the ``AWS_SHARED_CREDENTIALS_FILE`` environment variable.
57
58 .. code-block:: yaml
59
60 # demo.aws_ec2.yml
61 plugin: amazon.aws.aws_ec2
62
63 # Attach the default AWS profile
64 aws_profile: default
65
66 # You could use Jinja2 to attach the AWS profile from the environment variable.
67 aws_profile: "{{ lookup('env', 'AWS_PROFILE') | default('dev-profile', true) }}"
68
69 You can also set your AWS profile as an ENV variable:
70
71 .. code-block:: bash
72
73 export AWS_PROFILE='test-profile'
74
75
76 If your Ansible controller is running on an EC2 instance with an assigned IAM Role, the credential may be omitted.
77 See the documentation for the controller `for more details <https://docs.ansible.com/ansible-tower/latest/html/userguide/inventories.html#ug-source-ec2>`_.
78
79 You can also use the ARN of the IAM role to assume to perform the inventory lookup.
80 This can be useful for connecting across different accounts, or to limit user access.
81 To do so, you should specify the ``iam_role_arn``.
82 You should still provide AWS credentials with enough privilege to perform the AssumeRole action.
83
84 .. code-block:: yaml
85
86 # demo.aws_ec2.yml
87 plugin: amazon.aws.aws_ec2
88
89 iam_role_arn: arn:aws:iam::1234567890:role/assumed-ansible
90
91
92 Minimal Example
93 ===============
94
95 Fetch all hosts in us-east-1, the hostname is the public DNS if it exists, otherwise the private IP address.
96
97 .. code-block:: yaml
98
99 # demo.aws_ec2.yml
100 plugin: amazon.aws.aws_ec2
101
102 # This sets the region. If empty (the default) default this will include all regions, except possibly
103 # restricted ones like us-gov-west-1 and cn-north-1.
104 regions:
105 - us-east-1
106
107 After providing any required options, you can view the populated inventory with ``ansible-inventory -i demo.aws_ec2.yml --graph``:
108
109 .. code-block:: text
110
111 @all:
112 |--@aws_ec2:
113 | |--ip-10-210-0-189.ec2.internal
114 | |--ip-10-210-0-195.ec2.internal
115 |--@ungrouped:
116
117
118 Allowed Options
119 ===============
120
121 Some of the ``aws_ec2`` dynamic inventory plugin options are explained in detail below. For a full list see `the plugin documentation <https://docs.ansible.com/ansible/latest/collections/amazon/aws/aws_ec2_inventory.html#id3>`_.
122
123 ``hostnames``
124 -------------
125
126 ``hostnames`` option provides different settings to choose how the hostname will be displayed.
127
128 Some examples are shown below:
129
130 .. code-block:: yaml
131
132 hostnames:
133 # This option allows displaying the public ip addresses.
134 - ip-address
135
136 # This option allows displaying the private ip addresses using `tag:Name` as a prefix.
137 # `name` can be one of the options specified in http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options.
138 - name: 'private-ip-address'
139 separator: '_'
140 prefix: 'tag:Name'
141
142 # Using literal values for hostname
143 # # Hostname will be aws-test_literal
144 - name: 'test_literal'
145 separator: '-'
146 prefix: 'aws'
147
148 # To use tags as hostnames use the syntax `tag:Name=Value` to use the hostname `Name_Value`, or
149 # `tag:Name` to use the value of the Name tag. If value provided does not exist in the above options,
150 # it will be used as a literal string.
151 - name: 'tag:Tag1=Test1,Tag2=Test2'
152
153 # Use dns-name attribute as hostname
154 - dns-name
155
156 # You can also specify a list in order of precedence for hostname variables.
157 - ip-address
158 - dns-name
159 - tag:Name
160 - private-ip-address
161
162 By default, the inventory will only return the first match one of the ``hostnames`` entries.
163 You may want to get all the potential matches in your inventory, this also implies you will get
164 duplicated entries. To switch to this behavior, set the ``allow_duplicated_hosts`` configuration key to ``True``.
165
166 ``keyed_groups``
167 ----------------
168
169 You can create dynamic groups using host variables with the ``keyed_groups`` option. ``keyed_groups`` comes in a prefix and a key format.
170 The prefix will be the name of the host group that is to be concatenated with the key.
171
172 Some examples are shown below:
173
174 .. code-block:: yaml
175
176 keyed_groups:
177 # This creates host groups based on architecture.
178 - prefix: arch
179 key: architecture
180
181 # This creates host groups based on `x86_64` architecture.
182 - prefix: arch
183 key: architecture
184 value:
185 'x86_64'
186
187 # This creates host groups based on availability zone.
188 - prefix: az
189 key: placement.availability_zone
190
191 # If the EC2 tag Name had the value `redhat` the tag variable would be: `tag_Name_redhat`.
192 # Similarly, if a tag existed for an AWS EC2 instance as `Applications` with the value of `nodejs` the
193 # variable would be: `tag_Applications_nodejs`.
194 - prefix: tag
195 key: ec2_tags
196
197 # This creates host groups using instance_type, e.g., `instance_type_z3_tiny`.
198 - prefix: instance_type
199 key: instance_type
200
201 # This creates host groups using security_groups id, e.g., `security_groups_sg_abcd1234` group for each security group.
202 - key: 'security_groups|json_query("[].group_id")'
203 prefix: 'security_groups'
204
205 # This creates a host group for each value of the Application tag.
206 - key: ec2_tags.Application
207 separator: ''
208
209 # This creates a host group per region e.g., `aws_region_us_east_2`.
210 - key: placement.region
211 prefix: aws_region
212
213 # This creates host groups based on the value of a custom tag `Role` and adds them to a metagroup called `project`.
214 - key: ec2_tags['Role']
215 prefix: foo
216 parent_group: "project"
217
218 # This creates a common parent group for all EC2 availability zones.
219 - key: placement.availability_zone
220 parent_group: all_ec2_zones
221
222 # This creates a group per distro (distro_CentOS, distro_Debian) and assigns the hosts that have matching values to it,
223 # using the default separator "_".
224 - prefix: distro
225 key: ansible_distribution
226
227
228 ``groups``
229 ----------
230
231 It is also possible to create groups using the ``groups`` option.
232
233 Some examples are shown below:
234
235 .. code-block:: yaml
236
237 groups:
238 # This created two groups - `Production` and `PreProduction` based on tags
239 # These conditionals are expressed using Jinja2 syntax.
240 redhat: "'Production' in ec2_tags.Environment"
241 ubuntu: "'PreProduction' in ec2_tags.Environment"
242
243 # This created a libvpc group based on specific condition on `vpc_id`.
244 libvpc: vpc_id == 'vpc-####'
245
246
247 ``compose``
248 -----------
249
250 ``compose`` creates and modifies host variables from Jinja2 expressions.
251
252 .. code-block:: yaml
253
254 compose:
255 # This sets the ansible_host variable to connect with the private IP address without changing the hostname.
256 ansible_host: private_ip_address
257
258 # This sets location_vars variable as a dictionary with location as a key.
259 location_vars:
260 location: "east_coast"
261 server_type: "ansible_hostname | regex_replace ('(.{6})(.{2}).*', '\\2')"
262
263 # This sets location variable.
264 location: "'east_coast'"
265
266 # This lets you connect over SSM to the instance id.
267 ansible_host: instance_id
268 ansible_connection: 'amazon.aws.aws_ssm'
269
270 # This defines combinations of host servers, IP addresses, and related SSH private keys.
271 ansible_host: private_ip_address
272 ansible_user: centos
273 ansible_ssh_private_key_file: /path/to/private_key_file
274
275 # This sets the ec2_security_group_ids variable.
276 ec2_security_group_ids: security_groups | map(attribute='group_id') | list | join(',')
277
278 # Host variables that are strings need to be wrapped with two sets of quotes.
279 # See https://docs.ansible.com/ansible/latest/plugins/inventory.html#using-inventory-plugins for details.
280 ansible_connection: '"amazon.aws.aws_ssm"'
281 ansible_user: '"ssm-user"'
282
283
284 ``include_filters`` and ``exclude_filters``
285 -------------------------------------------
286
287 ``include_filters`` and ``exclude_filters`` options give you the ability to compose the inventory with several queries (see `available filters <http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options>`_).
288
289 .. code-block:: yaml
290
291 include_filters:
292 # This includes everything in the inventory that has the following tags.
293 - tag:Project:
294 - 'planets'
295 - tag:Environment:
296 - 'demo'
297
298 # This excludes everything from the inventory that has the following tag:Name.
299 exclude_filters:
300 - tag:Name:
301 - '{{ resource_prefix }}_3'
302
303
304 ``filters``
305 -----------
306
307 ``filters`` are used to filter out AWS EC2 instances based on conditions (see `available filters <http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options>`_).
308
309 .. code-block:: yaml
310
311 filters:
312 # This selects only running instances with tag `Environment` tag set to `dev`.
313 tag:Environment: dev
314 instance-state-name : running
315
316 # This selects only instances with tag `Environment` tag set to `dev` and `qa` and specific security group id.
317 tag:Environment:
318 - dev
319 - qa
320 instance.group-id: sg-xxxxxxxx
321
322 # This selects only instances with tag `Name` fulfilling specific conditions.
323 - tag:Name:
324 - dev-*
325 - share-resource
326 - hotfix
327
328
329 ``use_contrib_script_compatible_ec2_tag_keys`` and ``use_contrib_script_compatible_sanitization``
330 -------------------------------------------------------------------------------------------------
331
332 .. deprecated:: 11.2.0
333 The ``use_contrib_script_compatible_ec2_tag_keys`` option is deprecated and will be removed in a release after 2026-12-01.
334 Use the ``ec2_tags`` structure instead (e.g. ``ec2_tags.TAGNAME`` rather than ``ec2_tag_TAGNAME``).
335
336 .. deprecated:: 11.2.0
337 The ``use_contrib_script_compatible_sanitization`` option is deprecated and will be removed in a release after 2026-12-01.
338 Use Ansible's default group name sanitization instead.
339
340 ``use_contrib_script_compatible_ec2_tag_keys`` exposes the host tags with ec2_tag_TAGNAME keys like the old ec2.py inventory script when it's True.
341
342 By default the ``aws_ec2`` plugin is using a general group name sanitization to create safe and usable group names for use in Ansible.
343
344 ``use_contrib_script_compatible_sanitization`` allows you to override that, in efforts to allow migration from the old inventory script and matches the sanitization of groups when the script's replace_dash_in_groups option is set to False.
345 To replicate behavior of replace_dash_in_groups = True with constructed groups, you will need to replace hyphens with underscores via the regex_replace filter for those entries.
346
347 For this to work you should also turn off the TRANSFORM_INVALID_GROUP_CHARS setting, otherwise the core engine will just use the standard sanitization on top.
348
349 This is not the default as such names break certain functionality as not all characters are valid Python identifiers which group names end up being used as.
350
351 The use of this feature is discouraged and we advise to migrate to the new ec2_tags structure.
352
353 .. code-block:: yaml
354
355 # demo.aws_ec2.yml
356 plugin: amazon.aws.aws_ec2
357 regions:
358 - us-east-1
359 filters:
360 tag:Name:
361 - 'instance-*'
362 hostnames:
363 - tag:Name
364 use_contrib_script_compatible_sanitization: True
365 use_contrib_script_compatible_ec2_tag_keys: True
366
367 After providing any required options, you can view the populated inventory with ``ansible-inventory -i demo.aws_ec2.yml --list``:
368
369 .. code-block:: text
370
371 {
372 "_meta": {
373 "hostvars": {
374 "instance-01": {
375 "aws_ami_launch_index_ec2": 0,
376 "aws_architecture_ec2": "x86_64",
377 ...
378 "ebs_optimized": false,
379 "ec2_tag_Environment": "dev",
380 "ec2_tag_Name": "instance-01",
381 "ec2_tag_Tag1": "Test1",
382 "ec2_tag_Tag2": "Test2",
383 "ena_support": true,
384 "enclave_options": {
385 "enabled": false
386 },
387 ...
388 },
389 "instance-02": {
390 ...
391 "ebs_optimized": false,
392 "ec2_tag_Environment": "dev",
393 "ec2_tag_Name": "instance-02",
394 "ec2_tag_Tag1": "Test3",
395 "ec2_tag_Tag2": "Test4",
396 "ena_support": true,
397 "enclave_options": {
398 "enabled": false
399 },
400 ...
401 }
402 }
403 },
404 "all": {
405 "children": [
406 "aws_ec2",
407 "ungrouped"
408 ]
409 },
410 "aws_ec2": {
411 "hosts": [
412 "instance-01",
413 "instance-02"
414 ]
415 }
416 }
417
418
419 ``hostvars_prefix`` and ``hostvars_suffix``
420 -------------------------------------------
421
422 ``hostvars_prefix`` and ``hostvars_suffix`` allow to set up a prefix and suffix for host variables.
423
424 .. code-block:: yaml
425
426 # demo.aws_ec2.yml
427 plugin: amazon.aws.aws_ec2
428 regions:
429 - us-east-1
430 filters:
431 tag:Name:
432 - 'instance-*'
433 hostvars_prefix: 'aws_'
434 hostvars_suffix: '_ec2'
435 hostnames:
436 - tag:Name
437
438 Now the output of ``ansible-inventory -i demo.aws_ec2.yml --list``:
439
440 .. code-block:: text
441
442 {
443 "_meta": {
444 "hostvars": {
445 "instance-01": {
446 "aws_ami_launch_index_ec2": 0,
447 "aws_architecture_ec2": "x86_64",
448 "aws_block_device_mappings_ec2": [
449 {
450 "device_name": "/dev/sda1",
451 "ebs": {
452 "attach_time": "2022-06-27T09:04:57+00:00",
453 "delete_on_termination": true,
454 "status": "attached",
455 "volume_id": "vol-06e065bca44e6eae5"
456 }
457 }
458 ],
459 "aws_capacity_reservation_specification_ec2": {
460 "capacity_reservation_preference": "open"
461 }
462 ...,
463 },
464 "instance-02": {
465 ...,
466 }
467 }
468 },
469 "all": {
470 "children": [
471 "aws_ec2",
472 "ungrouped"
473 ]
474 },
475 "aws_ec2": {
476 "hosts": [
477 "instance-01",
478 "instance-02"
479 ]
480 }
481 }
482
483
484 ``strict`` and ``strict_permissions``
485 -------------------------------------
486
487 ``strict: False`` will skip instead of producing an error if there are missing facts.
488
489 ``strict_permissions: False`` will ignore 403 errors rather than failing.
490
491
492 ``use_ssm_inventory``
493 ---------------------
494
495 ``use_ssm_inventory: True`` enables fetching additional EC2 instance information from the AWS Systems Manager (SSM) inventory service into hostvars. By leveraging the SSM inventory data, the ``use_ssm_inventory`` option provides additional details and attributes about the EC2 instances in your inventory.
496 These details can include operating system information, installed software, network configurations, and custom inventory attributes defined in SSM.
497
498
499 ``route53_enabled``
500 ---------------------
501
502 ``route53_enabled: True`` enables to use the Route 53 DNS information as host name. The ``route53_hostnames`` option specifies the list of Route 53 DNS name suffix to consider while filtering host names while the ``route53_excluded_zones`` option specifies the list of Route53 host zones to exclude.
503
504 .. code-block:: yaml
505
506 # route53_inventory.aws_ec2.yml
507 plugin: aws_ec2
508 # This enables Route53 DNS information
509 route53_enabled: true
510 # Specifies the list of Route53 DNS zones to exclude
511 route53_excluded_zones:
512 - foo.bar.zone1
513 - foo.bar.zone2
514 # Specifies the list of Route53 DNS suffix to consider
515 route53_hostnames:
516 - example.net
517 - example.org
518
519 ``cache``
520 ---------
521
522 ``aws_ec2`` inventory plugin support caching can use the general settings for the fact cache defined in the ``ansible.cfg`` file's ``[defaults]`` section or define inventory-specific settings in the ``[inventory]`` section.
523 You can can define plugin-specific cache settings in the config file:
524
525 .. code-block:: yaml
526
527 # demo.aws_ec2.yml
528 plugin: aws_ec2
529 # This enables cache.
530 cache: yes
531 # Plugin to be used.
532 cache_plugin: jsonfile
533 cache_timeout: 7200
534 # Location where files are stored in the cache.
535 cache_connection: /tmp/aws_inventory
536 cache_prefix: aws_ec2
537
538 Here is an example of setting inventory caching with some fact caching defaults for the cache plugin used and the timeout in an ``ansible.cfg`` file:
539
540 .. code-block:: ini
541
542 [defaults]
543 fact_caching = ansible.builtin.jsonfile
544 fact_caching_connection = /tmp/ansible_facts
545 cache_timeout = 3600
546
547 [inventory]
548 cache = yes
549 cache_connection = /tmp/ansible_inventory
550
551
552 Complex Example
553 ===============
554
555 Here is an ``aws_ec2`` complex example utilizing some of the previously listed options:
556
557 .. code-block:: yaml
558
559 # demo.aws_ec2.yml
560 plugin: amazon.aws.aws_ec2
561 regions:
562 - us-east-1
563 - us-east-2
564 keyed_groups:
565 # add hosts to tag_Name_value groups for each aws_ec2 host's ec2_tags.Name variable.
566 - key: ec2_tags.Name
567 prefix: tag_Name_
568 separator: ""
569 groups:
570 # add hosts to the group dev if any of the dictionary's keys or values is the word 'dev'.
571 development: "'dev' in (ec2_tags|list)"
572 filters:
573 tag:Name:
574 - 'instance-01'
575 - 'instance-03'
576 include_filters:
577 - tag:Name:
578 - 'instance-02'
579 - 'instance-04'
580 exclude_filters:
581 - tag:Name:
582 - 'instance-03'
583 - 'instance-04'
584 hostnames:
585 # You can also specify a list in order of precedence for hostname variables.
586 - ip-address
587 - dns-name
588 - tag:Name
589 - private-ip-address
590 compose:
591 # This sets the `ansible_host` variable to connect with the private IP address without changing the hostname.
592 ansible_host: private_ip_address
593
594 If a host does not have the variables in the configuration above (i.e. ``ec2_tags.Name``, ``ec2_tags``, ``private_ip_address``), the host will not be added to groups other than those that the inventory plugin creates and the ``ansible_host`` host variable will not be modified.
595
596 Now the output of ``ansible-inventory -i demo.aws_ec2.yml --graph``:
597
598 .. code-block:: text
599
600 @all:
601 |--@aws_ec2:
602 | |--instance-01
603 | |--instance-02
604 |--@tag_Name_instance_01:
605 | |--instance-01
606 |--@tag_Name_instance_02:
607 | |--instance-02
608 |--@ungrouped:
609
610
611 Using Dynamic Inventory Inside Playbook
612 =======================================
613
614 If you want to use dynamic inventory inside the playbook, you just need to mention the group name in the hosts variable as shown below.
615
616 .. code-block:: yaml
617
618 ---
619 - name: Ansible Test Playbook
620 gather_facts: false
621 hosts: tag_Name_instance_02
622
623 tasks:
624 - name: Run Shell Command
625 command: echo "Hello World"