o .&apR@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZmZmZddlmZddlmZeeZdZejddZd Zd Zed ejZed Z ed Z!dZ"d#Z$ddZ%ddZ&GdddeZ'ddZ(ddZ)dS)N) ClientError) shlex_quoteurlopenensure_text_type) BasicCommand)!create_client_from_parsed_globalszOpsWorks-Instance)minutesz/AWS/OpsWorks/z7arn:aws:iam::aws:policy/AWSOpsWorksInstanceRegistrationz^(?!-)[a-z0-9-]{1,63}(?$AGENT_TMP_DIR/opsworks-agent-installer/preconfig <d?ZedEdAdBZedCdDZZS)Frr z Registers an EC2 instance or machine with AWS OpsWorks. Registering a machine using this command will install the AWS OpsWorks agent on the target machine and register it with an existing OpsWorks stack. zstack-idTzZA stack ID. The instance will be registered with the given stack.)namerequired help_textzinfrastructure-classec2 on-premiseszzSpecifies whether to register an EC2 instance (`ec2`) or an on-premises instance (`on-premises`).)rrchoicesrzoverride-hostnamehostnamezrThe instance hostname. If not provided, the current hostname of the machine will be used.)rdestrzoverride-private-ip private_ipaAAn IP address. If you set this parameter, the given IP address will be used as the private IP address within OpsWorks. Otherwise the private IP address will be determined automatically. Not to be used with EC2 instances.zoverride-public-ip public_ipa?An IP address. If you set this parameter, the given IP address will be used as the public IP address within OpsWorks. Otherwise the public IP address will be determined automatically. Not to be used with EC2 instances.z override-sshsshzmIf you set this parameter, the given command will be used to connect to the machine.z ssh-usernameusernamezXIf provided, this username will be used to connect to the host.zssh-private-key private_keyzhIf provided, the given private key file will be used to connect to the machine.local store_truezIf given, instead of a remote machine, the local machine will be imported. Cannot be used together with `target`.)ractionrzuse-instance-profilezRUse the instance profile instead of creating an IAM user.target?z []zEither the EC2 instance ID or the hostname of the instance or machine to be registered with OpsWorks. Cannot be used together with `--local`.)rpositional_argnargssynopsisrcs>tt||d|_d|_d|_d|_d|_d|_d|_ dSN) superr__init___stack _ec2_instance _prov_params _use_address _use_hostname _name_for_iam access_key)selfr __class__r rr,}s zOpsWorksRegister.__init__cCs"|jd|_t|jd||_dS)Niamopsworks)_session create_clientr7rr8r4argsparsed_globalsr r r_create_clientss z OpsWorksRegister._create_clientscCsL|||||||||||||||dSr*)r>prevalidate_argumentsretrieve_stackvalidate_argumentsdetermine_detailscreate_iam_entitiessetup_target_machiner;r r r _run_mains      zOpsWorksRegister._run_maincCs|js |js td|jr|jrtd|jr!tdkr!td|jr.|js*|jr.td|jdkrA|j r:td|j rAtd|jd krM|j rMtd |j r]t |j s_td |j d Sd S) zN Validates command line arguments before doing anything else. z%One of target or --local is required.z4Arguments target and --local are mutually exclusive.Linuxz6Non-Linux instances are not supported by AWS OpsWorks.zYArgument --override-ssh cannot be used together with --ssh-username or --ssh-private-key.rz/--override-private-ip is not supported for EC2.z.--override-public-ip is not supported for EC2.rz1--use-instance-profile is only supported for EC2.zxInvalid hostname: '%s'. Hostnames must consist of letters, digits and dashes only and must not start or end with a dash.N)r%r" ValueErrorplatformsystemrr r!infrastructure_classrruse_instance_profiler HOSTNAME_REmatchr4r<r r rr?sL     z&OpsWorksRegister.prevalidate_argumentscstd|jjjgddd|_|jj|jdd|_jdkrj std|j j d|jd d }d gi}gd |jvrP|d  d |jd gdn ddt jrdjg|d<n tjrx fddj|_n |d  djgdfdd|jdi|dD}|stdjt|dkrtdjddd|Df|d|_dSdSdS)z Retrieves the stack from the API, thereby ensures that it exists. Provides `self._stack`, `self._prov_params`, `self._use_address`, and `self._ec2_instance`. z,Retrieving stack and provisioning parameters)StackIdsStacksrStackIdrQrz#Retrieving EC2 instance informationRegion) region_nameFiltersVpcIdzvpc-id)NameValuescSsd|vS)NrVr instancer r rsz1OpsWorksRegister.retrieve_stack.. InstanceIdscs |djkp|djkS)NPrivateIpAddressPublicIpAddress)getr%rYr<r rr[sztag:Namecs4g|]}|dD]tfddDrqqS) Instancesc3s|]}|VqdSr*r ).0cir r z=OpsWorksRegister.retrieve_stack...)all)rbr) conditionsrdr sz3OpsWorksRegister.retrieve_stack.. Reservationsz&Did not find any instance matching %s.z)Found multiple instances matching %s: %s.z, css|]}|dVqdS) InstanceIdNr )rbrer r rrfrgz2OpsWorksRegister.retrieve_stack..Nr )LOGdebugr8describe_stacksstack_idr-&describe_stack_provisioning_parametersr/rJr"r9r:appendINSTANCE_ID_RErMr% IP_ADDRESS_REr0describe_instancesrGlenjoinr.)r4r<r desc_args instancesr )r<rjrr@sd           zOpsWorksRegister.retrieve_stackcsjr!|jj|jddd}tfdd|Dr!tdjjdkrAjrCt t t t  d}||jd krEtd d Sd Sd S) zS Validates command line arguments using the retrieved information. rQrRrac3s"|] }j|dkVqdS)HostnameN)rlower)rbrZr`r rrfsz6OpsWorksRegister.validate_arguments..z@Invalid hostname: '%s'. Hostnames must be unique within a stack.rregionrSz1The stack's and the instance's region must match.N)rr8rwr-anyrGrJr"jsonloadsrr IDENTITY_URLread)r4r<r{r~r r`rrA s4 z#OpsWorksRegister.validate_argumentscCs|js6|jrn/|jdkr-d|jvr|jd|_nd|jvr)td|jd|_n td|jdkr6|j|_|jrC|j|_ |j|_ dS|jrPd|_ t |_ dSd|_ |j|_ dS)a  Determine details (like the address to connect to and the hostname to use) from the given arguments and the retrieved data. Provides `self._use_address` (if not provided already), `self._use_hostname` and `self._name_for_iam`. rr^r]zYInstance does not have a public IP address. Trying to use the private address to connect.z1The instance does not seem to have an IP address.rN) r0r"rJr.rowarningrGr%rr1r2socket gethostnamerNr r rrB s0       z"OpsWorksRegister.determine_detailsc CsP|jr tdd|_dStddt|jd}z|jj|tdtd|Wn&t yQ}z|j di d d krFtd |nWYd}~nd}~wwtd d t t|jddt t|j df}tdD]D}||rxd|nd}z |jj|tdWn&t y}z|j di d d krtd|nWYd}~qod}~wwtd|ntdtd|jj||dz |jjt|dWn@t y}z3|j di d dkrtdt||jjt||jdt|dtdt|nWYd}~n d}~wwtdt|td |jj|d!d"|_dS)#zp Creates an IAM group, user and corresponding credentials. Provides `self.access_key`. zSkipping IAM entity creationNz#Creating the IAM group if necessaryz OpsWorks-%srQ) GroupNamePathzCreated IAM group %sErrorCodeEntityAlreadyExistszIAM group %s exists, continuingzCreating an IAM userzOpsWorks-%s-%srWz+%s)UserNamerz/IAM user %s already exists, trying another namezCreated IAM user %sz&Couldn't find an unused IAM user name.z3Adding the user to the group and attaching a policy)rr) PolicyArnr AccessDeniedzFUnauthorized to attach policy %s to user %s. Trying to put user policyArn) PolicyNamePolicyDocumentrzPut policy %s to user %szAttached policy %s to user %szCreating an access key)r AccessKey)rKrorpr3 clean_for_iamr-r7 create_groupIAM_PATHrresponser_ shorten_namer2range create_userrGadd_user_to_groupattach_user_policyIAM_POLICY_ARNput_user_policyIAM_USER_POLICY_NAME_iam_policy_documentIAM_USER_POLICY_TIMEOUTcreate_access_key)r4r< group_namee base_usernametry_r r r rrCGs              z$OpsWorksRegister.create_iam_entitiescCsjt|jd||||jddd}|jr(tdtdd|gd Std| ||d S) zz Setups the target machine by copying over the credentials and starting the installation process. AgentInstallerUrl Parametersassets_download_bucket)agent_installer_url preconfigrzRunning the installer locally/bin/sh-cz6Connecting to the target machine to run the installer.N) REMOTE_SCRIPTr/ _to_ruby_yaml_pre_config_documentr"rorp subprocess check_callr)r4r< remote_scriptr r rrDs   z%OpsWorksRegister.setup_target_machinec CsDtdkr]zOtjddd}||||jr|j}n!d}|jr*|d|j7}|jr4|d|j7}|d|j 7}|d 7}|d|j 7}t j |d d Wt |j dSt |j w|jritt|j}n d d g}|jrx|d|jg|jr|d|jg||j dd|g}|ddd|Dt |dS)zA Runs a (sh) script on a remote machine via SSH. WindowswtF)deleteplinkz -l "%s"z -i "%s"z "%s"z -mT)shellrz-ttz-lz-irr css|]}t|VqdSr*)r)rbwordr r rrfrgz'OpsWorksRegister.ssh..N)rHrItempfileNamedTemporaryFilewritecloserr r!r0rrrosremoveshlexsplitstrextendrtry)r4r<r script_filecall remote_callr r rrs8    zOpsWorksRegister.sshcCstdd|jdi|jd}|jr |jd|d<|jd|d<|jr(|j|d<|jr0|j|d <|jr8|j|d <|jd k|d <t d ||S)NrrrQr AccessKeyId access_key_idSecretAccessKeysecret_access_keyrrrrimportzUsing pre-config: %rr ) dictr-r/r3r1rrrJrorp)r4r< parametersr r rrs$    z%OpsWorksRegister._pre_config_documentNcCsNdd|d}|durtj|}dd|dii|d<|gdd }t|S) Nzopsworks:RegisterInstanceAllow)ActionEffectResource DateLessThanzaws:CurrentTimez%Y-%m-%dT%H:%M:%SZ Conditionz 2012-10-17) StatementVersion)datetimeutcnowstrftimerdumps)arntimeout statement valid_untilpolicy_documentr r rrs z%OpsWorksRegister._iam_policy_documentcCsdddt|DS)N css&|]\}}d|t|fVqdS)z:%s: %sN)rr)rbkvr r rrf sz1OpsWorksRegister._to_ruby_yaml..)rysorteditems)rr r rr s  zOpsWorksRegister._to_ruby_yamlr*)__name__ __module__ __qualname__NAMEtextwrapdedentstrip DESCRIPTION ARG_TABLEr,r>rEr?r@rArBrCrDrr staticmethodrr __classcell__r r r5rrEsp  .  'L'\( rcCstdd|S)z9 Cleans a name to fit IAM's naming requirements. z[^A-Za-z0-9+=,.@_-]+-)resub)rr r rrsrcCsDt||kr|St|dd\}}|d||d|| dS)z< Shortens a name to the given number of characters. Nz...)rxdivmod)r max_lengthqrir r rrs "r)*rrloggingrrHrrrrrrbotocore.exceptionsr awscli.compatrrrawscli.customizations.commandsrawscli.customizations.utilsr getLoggerrror timedeltarrrcompileIrLrurvrlstriprrr rrrr r r rsH         M