Task performs work despite conditional

Hi,

I have the following task

`

  • name: Create ec2 key pair using local key
    when: ec2_key_material is defined
    ec2_key:
    name: “{{ ec2_key_name }}”
    region: “{{ ec2_region }}”
    key_material: “{{ item }}”
    with_file: /path/to/public_key.id_rsa.pub
    `

Code was taking from http://docs.ansible.com/ec2_key_module.html

ec2_key_material is not defined

Whilst it does skip it tries to find the file. If I wanted to pass the file into the role and do the following

with_file: "{{ ec2_key_material }}"

I get

TASK: [openbet/aws/ec2-create-instance | Create ec2 key pair using local key] *** fatal: [localhost] => could not locate file in lookup: {{ ec2_key_material }}

If I add a real path then it logs out the key. I really don’t want that happening

TASK: [openbet/aws/ec2-create-instance | Create ec2 key pair using local key] *** skipping: [localhost] => (item=-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAkYI6Fxq0Qlxmn0rwWlyVX4VERtahcjZDFMA8VnJiPCcHMcGSZWmqkVusrm39 ..... 9B5yU8q4D9vEzuLYmbaRJji9YpTnPCHEHJ7Dn9a85UMIk+D0AYsHDMW3rqkovcsXhwft5CdIVDJ0 gNgSLOyND24AHxTwxBhHnAf3oSsoYpx5PgcT75ydE123nGFWa4siMZiV/vP4+ycOUF4= -----END RSA PRIVATE KEY-----)

Any suggestions. The latter issue seems worrying

Thanks

James

Try with_file: “{{ lookup(‘file’, ‘path/goes/here’ ) }}”

Hi,

That gives me the following

TASK: [openbet/aws/ec2-create-instance | Create ec2 key pair using local key] ***
fatal: [localhost] => could not locate file in lookup: -----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAkYI6Fxq0Qlxmn0rwWlyVX4VERtahcjZDFMA8VnJiPCcHMcGSZWmqkVusrm39
wIHi16uUwyj+D0BpoNEDy8mvaRvE9apwn2s/Ampyb8nQnHCNdx43wu+AIN3PG8PAfRbrcGlPpKpQ

The location is correct.

I’m running ansible-playbook 1.8.2

It still logs the private key which is iffy and

when: ec2_key_material is defined

isn’t stopping it from looking for the file. I would have thought it would have short circuited itself before doing any lookups

James

If you read the documentation page of this module careful enough, you will see that, in fact, the “{{ item }}” comes from the with_file, not from your vars. That is the material :slight_smile:

Hi,

Not sure I follow, I understand that {{ item }} comes from with_file. The same as other loops

Maybe i’m missing something and I apologise

All I want to achieve is to conditionally handle the key if the path to a key is specified.

I also don’t want it to log the key if its skipped and I want it to skip if the path isn’t specified.

The docs don’t mention using lookup

Regarding the second point. This post helped correct the saving .pem logic

http://grokbase.com/t/gg/ansible-project/147an12dj4/how-to-skip-local-action-if-file-exists

try:

with_file: "{{ ec2_key_material|default }}"

with_ lookups always happen before the when clause (to allow for use
of item in when), so if you don't specify a key this will be an error.

Perfect thanks