How do you add an EC2 instance created with ec2 module to ~/.ssh/known_hosts

Let’s say I have this ec2 task (taken from the documentation) in a file named site.yml:

`

Basic provisioning example

  • ec2:
    key_name: mykey
    instance_type: t2.micro
    image: ami-123456
    wait: yes
    group: webserver
    count: 3
    vpc_subnet_id: subnet-29e63245
    assign_public_ip: yes
    `

Assuming I register the ec2 module result into a variable named ec2_instances, what would I do to add that single ec2 instance to my ~/.ssh/known_hosts file so that I can easily ssh into the new instance?

I’ve looked at the known_hosts module and its example is:

`

  • name: tell the host about our servers it might want to ssh to
    known_hosts:
    path: /etc/ssh/ssh_known_hosts
    name: foo.com.invalid
    key: “{{ lookup(‘file’, ‘pubkeys/foo.com.invalid’) }}”
    `

Every property makes sense to me except for the key property. Regarding the lookup plugin, I don’t have any file containing public keys for my new instance (that I know of). What should I provide for the key property?

The documentation for the key property is:

The SSH public host key, as a string (required if state=present, optional when state=absent, in which case all keys for the host are removed). The key must be in the right format for ssh (see sshd(8), section “SSH_KNOWN_HOSTS FILE FORMAT”)

I have looked into the sshd(8) manual entry and here are the relevant paragraphs (emphasis mine):

Each line in these files contains the following fields: markers (optional), hostnames, keytype, base64-encoded key, comment. The fields are separated by spaces.

The keytype and base64-encoded key are taken directly from the host key; they can be obtained, for example, from /etc/ssh/ssh_host_rsa_key.pub. The optional comment field continues to the end of the line, and is not used.

How do I get the key I need to add to the file? This sounds like a common task so before I put forth potentially unnecessary effort to build my own solution, I thought I’d check to see if I was just missing something.

Thanks!