It would seem that you have a fundamental misunderstanding of how AWS instances work. When an instance is created, it has a key pair assigned to it for the user by default. (for example, for an Amazon Linux instance, the user will be an ec2 user, ubuntu images use the ubuntu user).
This key pair can be seen in the ec2 console for an instance in it. All existing key pairs can be seen in the Keyboard Pairs section of the ec2 console.
To be able to ssh into an instance that you start with the key you just created, you need to do a few things:
- Create a key pair locally (use
shell: ssh-keygen ... ) - Create an ec2 key pair from a locally generated key pair (use
ec2_key: ... ) - Run the instance using the ec2 named key pair (use
ec2: ... ) - Call the instance just launched in the same tutorial using the key generated in step 1.
Steps 1-3 should be run as hosts: 127.0.0.1 .
Step 4 should be performed as a separate call to hosts: in the same book and not as simple as it seems. You will need to somehow specify the newly created instance in the hosts , the Ansible group_vars , using the add_hosts module and / or find its IP address in some way (possibly using instance tags).
After the instance is found, the Ansible private_key_file variable can then be used to specify the key in step 1 and ssh in the instance.
Not that this could not be done, but because of the complexity and impracticality of doing this in order to have a new key pair every time you insert an instance into an instance, I would advise this if it was not absolutely necessary. It would be better to have the right key rotation policies if this is a security issue.
source share