How do I create a new key in Ansible using the ec2_key module?
I don't know how to use the ec2_key module in Ansible. Can someone please give me an example on how to create a new Key-Pair?
+3
SPM
source
to share
3 answers
working example:
- name: Create an EC2 key
ec2_key:
name: "mykey"
region: "eu-west-1"
register: ec2_key
- name: save private key
copy:
content: "{{ ec2_key.key.private_key }}"
dest: "./aws-private.pem"
mode: 0600
when: ec2_key.changed
+7
Arbab Nazar
source
to share
The examples in the Ansible documentation show exactly how to do this:
# Creates a new ec2 key pair named `example` if not present, returns generated
# private key
- name: example ec2 key
local_action:
module: ec2_key
name: example
# Creates a new ec2 key pair named `example` if not present using provided key
# material
- name: example2 ec2 key
local_action:
module: ec2_key
name: example2
key_material: 'ssh-rsa AAAAxyz...== me@example.com'
state: present
# Creates a new ec2 key pair named `example` if not present using provided key
# material
- name: example3 ec2 key
local_action:
module: ec2_key
name: example3
key_material: "{{ item }}"
with_file: /path/to/public_key.id_rsa.pub
+4
Bruce P
source
to share
But you cannot save the generated private key , so this method is not suitable. Instead of using the ec2_key module, use the command module and use the aws cli to create and store the private key in the pem file. eg.
- command: /usr/local/bin/aws ec2 create-key-pair --key-name keypair_name > ~/keypair_name.pem
register: keypair
-1
Hardeep singh
source
to share